/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.project.web.dynamic;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.common.utils.MyBeanUtils;
import com.jeeplus.modules.project.entity.ProjectInfo;
import com.jeeplus.modules.project.entity.ProjectMember;
import com.jeeplus.modules.project.service.ProjectInfoService;
import com.jeeplus.modules.sys.entity.Office;
import com.jeeplus.modules.sys.entity.User;
import com.jeeplus.modules.sys.service.OfficeService;
import com.jeeplus.modules.sys.service.SystemService;
import com.jeeplus.modules.sys.utils.DictUtils;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.sys.utils.WeChatTokenUtil;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.modules.project.entity.dynamic.ProjectDynamic;
import com.jeeplus.modules.project.service.dynamic.ProjectDynamicService;

/**
 * 项目动态Controller
 * @author 卢经纬
 * @version 2019-04-10
 */
@Controller
@RequestMapping(value = "${adminPath}/project/dynamic/projectDynamic")
public class ProjectDynamicController extends BaseController {

	@Autowired
	private ProjectDynamicService projectDynamicService;
	@Autowired
	private ProjectInfoService projectInfoService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SystemService systemService;

	@ModelAttribute
	public ProjectDynamic get(@RequestParam(required=false) String id) {
		ProjectDynamic entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = projectDynamicService.get(id);
		}
		if (entity == null){
			entity = new ProjectDynamic();
		}
		return entity;
	}

	/**
	 * 项目动态列表页面
	 */
	@RequiresPermissions("project:dynamic:projectDynamic:list")
	@RequestMapping(value = {"list", ""})
	public String list(ProjectDynamic projectDynamic, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectDynamic> page = projectDynamicService.findPage(new Page<ProjectDynamic>(request, response), projectDynamic);
		model.addAttribute("page", page);
		return "modules/project/dynamic/projectDynamicList";
	}
	/**
	 * 微信项目动态详情界面
	 */
	@RequestMapping(value = "/weChatDetail")
	public String weChatDetail(ProjectInfo projectInfo, HttpServletRequest request, HttpServletResponse response, Model model) {
		ArrayList<ProjectDynamic> list_all = (ArrayList<ProjectDynamic>)projectDynamicService.findListByProject(projectInfo);
		ArrayList<ProjectDynamic> list = new ArrayList<ProjectDynamic>();
		if (StringUtils.isNoneBlank(projectInfo.getStage())) {
			for (int i = 0; i < list_all.size(); i++) {
				if (projectInfo.getStage().equals("") || projectInfo.getStage() == null) {
					list = list_all;
					break;
				}else if (projectInfo.getStage().equals(list_all.get(i).getStage().toString())) {
					list.add(list_all.get(i));
				}
			}
		}else {
			list = list_all;
		}
		projectInfo = projectInfoService.get(projectInfo.getId());
		model.addAttribute("list", list);
		model.addAttribute("projectInfo", projectInfo);
		StringBuffer projectMember = new StringBuffer();
		User user = projectInfo.getProjectMemberList().get(0).getTuser();
		for (int i = 0; i < projectInfo.getProjectMemberList().size(); i++) {
			if (i == 0 ) {
				projectMember.append(projectInfo.getProjectMemberList().get(i).getTuser().getName());
			}else{
				projectMember.append("、" +projectInfo.getProjectMemberList().get(i).getTuser().getName());
			}

		}
		model.addAttribute("projectMember", projectMember);
		return "modules/project/dynamic/projectDynamicWeChatDetail";
	}
	/**
	 * 微信项目动态详情界面
	 * @throws Exception
	 */
	@RequestMapping(value = "/weChatAdd")
	public String weChatAdd(ProjectDynamic projectDynamic, Model model) throws Exception {
		model.addAttribute("projectDynamic", projectDynamic);
		return "modules/project/dynamic/projectDynamicWeChatAdd";
	}

	/**
	 * 查看，增加，编辑项目动态表单页面
	 */
	@RequiresPermissions(value={"project:dynamic:projectDynamic:view","project:dynamic:projectDynamic:add","project:dynamic:projectDynamic:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProjectDynamic projectDynamic, Model model) {
		model.addAttribute("projectDynamic", projectDynamic);
		return "modules/project/dynamic/projectDynamicForm";
	}

	/**
	 * 保存项目动态
	 */
	@RequiresPermissions(value={"project:dynamic:projectDynamic:add","project:dynamic:projectDynamic:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(ProjectDynamic projectDynamic, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, projectDynamic)){
			return form(projectDynamic, model);
		}
		if(!projectDynamic.getIsNewRecord()){//编辑表单保存
			ProjectDynamic t = projectDynamicService.get(projectDynamic.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(projectDynamic, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			projectDynamicService.save(t);//保存
		}else{//新增表单保存
			projectDynamicService.save(projectDynamic);//保存
		}
		addMessage(redirectAttributes, "保存项目动态成功");
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}

	/**
	 * 微信保存项目动态
	 */
	@RequestMapping(value = "weChatSave")
	public String weChatSave(ProjectDynamic projectDynamic, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, projectDynamic)){
			return weChatAdd(projectDynamic, model);
		}
		if(!projectDynamic.getIsNewRecord()){//编辑表单保存
			ProjectDynamic t = projectDynamicService.get(projectDynamic.getId());//从数据库取出记录的值
			MyBeanUtils.copyBeanNotNull2Bean(projectDynamic, t);//将编辑表单中的非NULL值覆盖数据库记录中的值
			projectDynamicService.save(t);//保存
		}else{//新增表单保存
			projectDynamicService.save(projectDynamic);//保存
		}
		StringBuffer touser = new StringBuffer();
		ProjectInfo projectInfo = projectInfoService.get(projectDynamic.getProjectInfo().getId());
		//推送给项目经理、部门成员和部门负责人
//		User user = UserUtils.getUser();
//		String[] offId = user.getOffice().getParentIds().split(",");
//		List<Office> offices = new ArrayList<Office>();
//		for (int i = 0; i <= offId.length; i++) {
//			if (i == offId.length) {
//				Office office = officeService.get(user.getOffice().getId());
//				offices.add(office);
//			} else {
//				if (!offId[i].equals("0")) {
//					Office office = officeService.get(offId[i]);
//					offices.add(office);
//				}
//			}
//
//		}
		Set<String> set = new HashSet<String>();
//		for (int i = 0; i < offices.size(); i++) {
//			if (offices.get(i).getPrimaryPerson() != null) {
//				set.add(offices.get(i).getPrimaryPerson().getLoginName());
//			}else if(offices.get(i).getDeputyPerson() != null){
//				set.add(offices.get(i).getDeputyPerson().getLoginName());
//			}
//		}
		List<ProjectMember> members = projectInfo.getProjectMemberList();
		for (int j = 0; j < members.size(); j++) {
			set.add(members.get(j).getTuser().getLoginName());
		}
		set.add(UserUtils.get(projectInfo.getProjectManager().getId()).getLoginName());
		for (String str : set) {
			if (touser.length() == 0) {
				touser.append(str);
			}else{
				touser.append("|" + str);
			}
		}
		String content = "【"+projectInfo.getProjectName()+":"+ DictUtils.getDictLabel(String.valueOf(projectDynamic.getStage()), "stage", "")+"阶段】"+UserUtils.getUser().getName()
				+"："+projectDynamic.getContent();
		logger.info("推送给了"+touser.toString()+"内容为："+content);
		WeChatTokenUtil.sendTextMsg(touser.toString(), "", "",1000006, content, 0);
		addMessage(redirectAttributes, "保存项目动态成功");
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/weChatDetail?id="+projectDynamic.getProjectInfo().getId();
	}


	/**
	 * 删除项目动态
	 */
	@RequiresPermissions("project:dynamic:projectDynamic:del")
	@RequestMapping(value = "delete")
	public String delete(ProjectDynamic projectDynamic, RedirectAttributes redirectAttributes) {
		projectDynamicService.delete(projectDynamic);
		addMessage(redirectAttributes, "删除项目动态成功");
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}

	/**
	 * 批量删除项目动态
	 */
	@RequiresPermissions("project:dynamic:projectDynamic:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			projectDynamicService.delete(projectDynamicService.get(id));
		}
		addMessage(redirectAttributes, "删除项目动态成功");
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("project:dynamic:projectDynamic:export")
	@RequestMapping(value = "export", method=RequestMethod.POST)
	public String exportFile(ProjectDynamic projectDynamic, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "项目动态"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
			Page<ProjectDynamic> page = projectDynamicService.findPage(new Page<ProjectDynamic>(request, response, -1), projectDynamic);
			new ExportExcel("项目动态", ProjectDynamic.class).setDataList(page.getList()).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出项目动态记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("project:dynamic:projectDynamic:import")
	@RequestMapping(value = "import", method=RequestMethod.POST)
	public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProjectDynamic> list = ei.getDataList(ProjectDynamic.class);
			for (ProjectDynamic projectDynamic : list){
				try{
					projectDynamicService.save(projectDynamic);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条项目动态记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条项目动态记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入项目动态失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}

	/**
	 * 下载导入项目动态数据模板
	 */
	@RequiresPermissions("project:dynamic:projectDynamic:import")
	@RequestMapping(value = "import/template")
	public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
			String fileName = "项目动态数据导入模板.xlsx";
			List<ProjectDynamic> list = Lists.newArrayList();
			new ExportExcel("项目动态数据", ProjectDynamic.class, 1).setDataList(list).write(response, fileName).dispose();
			return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/project/dynamic/projectDynamic/?repage";
	}


	/**
	 * 选择项目名称
	 */
	@RequestMapping(value = "selectprojectInfo")
	public String selectprojectInfo(ProjectInfo projectInfo, String url, String fieldLabels, String fieldKeys, String searchLabel, String searchKey, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProjectInfo> page = projectDynamicService.findPageByprojectInfo(new Page<ProjectInfo>(request, response),  projectInfo);
		try {
			fieldLabels = URLDecoder.decode(fieldLabels, "UTF-8");
			fieldKeys = URLDecoder.decode(fieldKeys, "UTF-8");
			searchLabel = URLDecoder.decode(searchLabel, "UTF-8");
			searchKey = URLDecoder.decode(searchKey, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		model.addAttribute("labelNames", fieldLabels.split("\\|"));
		model.addAttribute("labelValues", fieldKeys.split("\\|"));
		model.addAttribute("fieldLabels", fieldLabels);
		model.addAttribute("fieldKeys", fieldKeys);
		model.addAttribute("url", url);
		model.addAttribute("searchLabel", searchLabel);
		model.addAttribute("searchKey", searchKey);
		model.addAttribute("obj", projectInfo);
		model.addAttribute("page", page);
		return "modules/sys/gridselect";
	}

}